package ge.unihack.instantdj.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpUtils {

	public static Map<String, String> newMap(String key, String value) {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(key, value);
		return map;
	}

	public static Map<String, String> getMap(String key, String value, Map<String, String> map) {
		map.put(key, value);
		return map;
	}

	public static void getAsync(final String url,
			final Map<String, String> map, final OnResultListener l) {
		new Thread() {
			@Override
			public void run() {
				try {
					int code = get(url, map);
					if (l != null) {
						l.onResult(code, null);
					}
				} catch (Exception err) {
					if (l != null) {
						l.onResult(-1, err);
					}
				}
			}
		}.start();
	}

	public static int get(String url, Map<String, String> map) throws IOException {
		int code = -1;
		HttpURLConnection con = null;
		try {
			con = openConnectionForGet(url, map);;
			con.setDoOutput(true);
			code = con.getResponseCode();
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}
		return code;
	}

	public static String getAdminIp(String url) throws IOException {
		HttpURLConnection con = null;
		try {
			con = openConnectionForGet(url, null);
			InputStream in = con.getInputStream();
			try {
				return readToEnd(in);
			} finally {
				in.close();
			}
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}
	}
	
	private static HttpURLConnection openConnectionForGet(String url, Map<String, String> map) throws IOException {
		StringBuilder ub = new StringBuilder(url);
		if (map != null) {
			Set<String> keySet = map.keySet();
			int c = 0, size = keySet.size();
			for (String key : keySet) {
				ub.append(key).append("=").append(map.get(key));
				if (++c != size) {
					ub.append("&");
				}
			}
		}
		return (HttpURLConnection) new URL(ub.toString()).openConnection();
	}

	public static boolean isOk(int code) {
		return code / 100 == 2;
	}
	
	public static String readToEnd(InputStream in) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		StringBuilder sb = new StringBuilder();
		String line;
		while ( (line = br.readLine()) != null) {
			sb.append(line);
		}
		return sb.toString();
	}

	public interface OnResultListener {

		void onResult(int code, Exception err);
	}

}
